package wickethub.data;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.NIOFSDirectory;

import com.google.inject.Provider;
import com.google.inject.Singleton;

/**
 * 
 * @author ftreacy
 *
 */
@Singleton
public class SearcherProvider implements Provider<IndexSearcher> { 

	private static final Log log = LogFactory.getLog(SearcherProvider.class);
	private IndexSearcher searcher;
	
	@SuppressWarnings("deprecation")
	public SearcherProvider() {
		
		try {
			
			File luceneDir = new File(Util.getLuceneDirectory());
			luceneDir.mkdirs();
			// if directory is empty, create an empty index
			if (luceneDir.list().length == 0) {
				new IndexWriter(luceneDir, new StandardAnalyzer(), true);
			}
			
			Directory dir = NIOFSDirectory.getDirectory(luceneDir);
			dir.clearLock("write.lock");
			searcher = new IndexSearcher(IndexReader.open(dir, true));
		} catch (Exception e) {
			throw new RuntimeException("Couldn't create IndexSearcher", e);
		}
		
	}
	
	public IndexSearcher get() {
		// the same instance of indexsearcher is returned as it's thread-safe
		return searcher;
	}
	
	public void triggerIndexReopen() {
		
		try {
			IndexReader reader = searcher.getIndexReader();
			
			if (!reader.isCurrent()) {
				IndexReader newReader = reader.reopen();
				reader.close();
				searcher = new IndexSearcher(newReader);
			}
			
		} catch (Exception e) {
			// if it can't reopen the reader, there's nothing great we can do but log it
			log.error("Something went wrong reopening the index", e);
		}
		
	}
	
}